/*
 * This file is part of the Try! Engine project.
 *
 * Copyright 2010-2011 Emanuele Bertoldi. All rights reserved.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * You should have received a copy of the modified BSD License along with this
 * program. If not, see <http://www.opensource.org/licenses/bsd-license.php>
 */

#include "tool.h"
#include "toolmodellist.h"

using namespace Try;

Tool::Tool(const QString& name, const QString& icon, QObject* parent)
    :   QObject(parent),
        m_name(name),
        m_icon(icon),
        m_targetView(0)
{
    ToolModelList::instance()->addTool(this);
}

Tool::~Tool()
{
    this->activate(0);

    ToolModelList::instance()->removeTool(this);
}

QString Tool::name() const
{
    return m_name;
}

QString Tool::icon() const
{
    return m_icon;
}

bool Tool::isActive() const
{
    return (m_targetView != 0);
}

void Tool::setName(const QString& name)
{
    if (name != m_name)
    {
        m_name = name;

        emit changed();
    }
}

void Tool::setIcon(const QString& icon)
{
    if (icon != m_icon)
    {
        m_icon = icon;

        emit changed();
    }
}

void Tool::activate(View3d* view)
{
    if (view != m_targetView)
    {
        if (m_targetView && !view)
            m_targetView->removeEventFilter(this);

        if (view)
        {
            ToolModelList* tools = ToolModelList::instance();

            for (int i=0; i<tools->rowCount(); ++i)
                tools->toolAt(i)->activate(0);
        }

        m_targetView = view;

        if (m_targetView)
            m_targetView->installEventFilter(this);

        emit activationChanged();
    }
}

View3d* Tool::targetView() const
{
    return m_targetView;
}
